package com.example.demo.controller;

import com.example.demo.dao.CityRepository;
import com.example.demo.entity.City;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
public class CityController {

    @Autowired
    private CityRepository userService;
    /**
     * 列表查询
     * @return
     */
    @GetMapping(value = "/listcity")
    private Map<String, Object> listCity() {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<City> cities = userService.findAll();
        modelMap.put("cityList", cities);
        return modelMap;
    }

    /**
     * areaid 查询
     * @param id
     * @return
     */
    @GetMapping(value = "/getcitybyid")
    private Map<String, Object> getCityById(Long id) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
      Optional <City> city = userService.findById(id);
        modelMap.put("city", city);
        return modelMap;
    }



    /**
     * 添加area
     * @param city
     * @return
     */
    @PostMapping(value = "/addcity")
    private Map<String, Object> addCity(@RequestBody City city) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        userService.save(city);
        boolean isSuccess = false;
        if(  city != null)  isSuccess = true;
            modelMap.put("success", isSuccess);
        return modelMap;
    }

    /**
     * 修改
     * @param city
     * @return
     */
    @PostMapping(value = "/modifycity")
    private Map<String, Object> modifyCity(@RequestBody City city) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
         userService.saveAndFlush(city);
        boolean b = false;
        if(city!= null)  b=true;
        modelMap.put("success", b);
        return modelMap;
    }

    /**
     * 删除area
     * @param id
     * @return
     */
    @GetMapping(value = "/removecity")
    private Map<String, Object> removeCity(Long id) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        Optional <City> city = userService.findById(id);
        boolean isSuccess = false;
        if(city != null) {
            userService.deleteById(id);
             isSuccess = true;
        }
        modelMap.put("success", isSuccess);
        return modelMap;
    }


}
